import os


def thumbnail_image(ori_image_path, output_image_path):
    from PIL import Image, ImageFile

    # 防止图片超过178956970 pixels 而报错
    ImageFile.LOAD_TRUNCATED_IMAGES = True
    Image.MAX_IMAGE_PIXELS = None

    ori_photo = Image.open(ori_image_path)  # 读取img文件
    if ori_photo.mode in ("RGBA", "LA"):
        ori_photo = ori_photo.convert("RGB")
    width, height = ori_photo.size
    while width > 500 or height > 500:
        width, height = width / 2, height / 2
    resized_image = ori_photo.resize((int(width), int(height)))
    with open(output_image_path, "wb") as f:
        resized_image.save(f, format="JPEG", quality=70)
    print("图片保存成功")


def write_image_to_local(file, output_image_path):
    with open(output_image_path, "wb") as f:
        for io in file.chunks():
            f.write(io)
    thumbnail_image(output_image_path, os.path.join(output_image_path.replace(".JPG", "_small.JPG")))
